from django.shortcuts import render,redirect

# Create your views here.
from db import  models
import  time
import os
from fileadmin import settings
def login(request):
    if request.method == "GET":
        user = request.session.get("user_name")
        admin_user_status =  models.userinfo.objects.filter(user_name="admin").count()
        if admin_user_status == 0:
            models.userinfo.objects.create(user_name="admin",user_password="123")
        if request.session.get("user_name"):
            user_status = models.userinfo.objects.filter(user_name=user).values("user_status")[0]["user_status"]
            if user_status == "1":

                info = {"user_name":user}
                log_list = models.log_record.objects.values().order_by('-log_id')[:100]
                info["log_list"] = log_list
                return render(request, "other/index.html",info)
            else:
                return redirect("/user/myfile/")
        else:
            return  render(request,"login.html")
    else:
        user = request.POST.get("user_name")
        user_password = request.POST.get("user_password")
        user_status = models.userinfo.objects.filter(user_name=user,user_password=user_password).count()
        if user_status == 0:
            return redirect("/user/login")
        else:
            user_active = \
            models.userinfo.objects.filter(user_name=user, user_password=user_password).values("user_active")[0][
                "user_active"]
            if user_active == 1:
                return redirect("/user/login")
            user_status = models.userinfo.objects.filter(user_name=user).values("user_status")[0]["user_status"]
            user_project = models.userinfo.objects.filter(user_name=user).values("user_project__project_alias","user_project__project_id")
            info = {"user_name": user,"user_project":user_project}
            request.session['user_name'] = user
            if user_status == "1":
                project_list = models.projectinfo.objects.values
                info["project_list"] = project_list
                log_list = models.log_record.objects.values().order_by('-log_id')[:100]
                info["log_list"] = log_list
                return render(request,"other/index.html",info)
            else:
                return redirect("/user/login/")

def userdel(request):
    if request.method == "GET":
        id = request.GET.get("id")
        user_name = models.userinfo.objects.filter(user_id=id).values("user_name")[0]["user_name"]
        if user_name == "admin":
            return redirect("/user/userlist")
        else:
            user = request.session.get("user_name")
            models.userinfo.objects.filter(user_id=id).delete()
            models.log_record.objects.create(user_name=user,log_content="删除用户%s" %(user_name),log_ctime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            return redirect("/user/userlist")

def useradd(request):
    user= request.session.get("user_name")
    info = {"user_name": user}
    if request.method == "GET":
        project_list = models.projectinfo.objects.values()
        info["project_list"] = project_list
        return render(request,"other/useradd.html",info)
    else:
        user_name = request.POST.get("user_name")
        user_alias = request.POST.get("user_alias")
        user_password = request.POST.get("user_password")
        user_status = request.POST.get("user_status")
        user_project = request.POST.getlist("user_project")
        user_show =  request.POST.get("user_show")
        user_del_file =  request.POST.get("user_del_file")
        user_insert = models.userinfo.objects.create(user_name=user_name,user_alias=user_alias,user_password=user_password,
                                                     user_status=user_status,user_show=user_show,user_del_file=user_del_file)
        id = user_insert.user_id
        obj = models.userinfo.objects.get(user_id=int(id))
        obj.user_project.add(*user_project)
        models.log_record.objects.create(user_name=user, log_content="添加用户%s" %(user_name),
                                             log_ctime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        return redirect("/user/userlist")


def userlist(request):
    user_name = request.session.get("user_name")
    if  request.method == "GET":
        user_list_tmp = models.userinfo.objects.values("user_id","user_name","user_status","user_alias","user_active","user_show")
        user_list = []
        for i in user_list_tmp:
            user_project_list = models.userinfo.objects.filter(user_id=i["user_id"]).values("user_project__project_name")
            user_project_dir = []
            for p in user_project_list:
                user_project_dir.append(p["user_project__project_name"])
            i["user_project_dir"] = user_project_dir
            user_list.append(i)

        info = {"user_name":user_name,"user_list":user_list}
        return render(request,"other/userlist.html",info)
    else:
        pass

def userupdate(request):
    user_name = request.session.get("user_name")
    if request.method == "GET":
        user_id = request.GET.get("id")
        user_info = models.userinfo.objects.filter(user_id=user_id).values("user_id","user_name","user_alias","user_password")[0]
        project_list = models.projectinfo.objects.values()
        info = {"user_name": user_name, "user_info": user_info,"project_list":project_list}
        return  render(request,"other/userupdate.html",info)
    else:
        user_id = request.GET.get("id")
        user_alias =  request.POST.get("user_alias")
        user_password =  request.POST.get("user_password")
        user_status =  request.POST.get("user_status")
        user_project = request.POST.getlist("user_project")
        user_active =  request.POST.get("user_active")
        user_show = request.POST.get("user_show")
        user_del_file = request.POST.get("user_del_file")
        models.userinfo.objects.filter(user_id=user_id).update(user_alias=user_alias,user_password=user_password,
                                                               user_status=user_status,user_active=user_active,
                                                               user_show=user_show,user_del_file=user_del_file)
        obj = models.userinfo.objects.get(user_id=int(user_id))
        obj.user_project.set(user_project)
        models.log_record.objects.create(user_name=user_name,log_content="用户资料被更新%s" %(user_alias),log_ctime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        return redirect("/user/userlist/")

def logout(request):
    if request.method == "GET":
        del request.session['user_name']
        request.session.flush()
        return redirect("/user/login")
def myfile(request):
    user = request.session.get("user_name")
    user_show_status = models.userinfo.objects.filter(user_name=user).values("user_show")[0]["user_show"]
    user_del_file =  models.userinfo.objects.filter(user_name=user).values("user_del_file")[0]["user_del_file"]
    if user_show_status == "0":
        user_project = models.userinfo.objects.filter(user_name=user).values("user_project__project_alias",
                                                                             "user_project__project_id")
    elif user_show_status == "1":
        user_project = models.userinfo.objects.filter(user_name=user).values("user_project__project_alias",
                                                                             "user_project__project_id")
    elif user_show_status == "2":
        user_project = models.userinfo.objects.values("user_project__project_alias","user_project__project_id").distinct()

    info = {"user_name": user, "user_project": user_project,"user_del_file":user_del_file}
    user_id = models.userinfo.objects.filter(user_name=user).values("user_id")[0]["user_id"]

    if request.method == "POST":

        project_id =  request.POST.get("project_id")
        project_name =  models.projectinfo.objects.filter(project_id=project_id).values("project_name")[0]["project_name"]
        userfile =  request.FILES.get("userfile")
        file_md5 =  request.POST.get("file_md5")
        base_dir=settings.STATICFILES_DIRS
        path_dir = "%s/apk/%s" %(base_dir[0],project_name)
        print(path_dir)
        if os.path.exists(path_dir):
            pass
        else:
            os.mkdir(path_dir)
        f = open(os.path.join(path_dir,userfile.name),'wb')
        for chunk in userfile.chunks():
            f.write(chunk)
        f.close()
        file_ctime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        url = models.sysconfig.objects.values("apk_url")[0]["apk_url"]
        file_url = url + "/static/apk/%s/%s" %(project_name,userfile.name)
        web_path = url
        file_path = "/static/apk/%s/%s" %(project_name,userfile.name)
        file_status = models.fileinfo.objects.filter(file_url=file_url).values().count()
        if file_status == 0:
            file_result = models.fileinfo.objects.create(file_name=userfile.name,file_ctime=file_ctime,file_url=file_url,
                                                         file_md5=file_md5,file_path=file_path,web_path=web_path)
            obj =  models.fileinfo.objects.get(file_id=file_result.file_id)
            obj.file_user.set([user_id])
            obj.file_project.set([project_id])

        else:
            file_id = models.fileinfo.objects.filter(file_url=file_url).values("file_id")[0]["file_id"]
            file_result = models.fileinfo.objects.filter(file_url=file_url).update(file_name=userfile.name, file_ctime=file_ctime,
                                                         file_url=file_url, file_md5=file_md5,file_cdn_status="888",
                                                                                   file_path=file_path,web_path=web_path)
            obj = models.fileinfo.objects.get(file_id=file_id)
            obj.file_user.set([user_id])
            obj.file_project.set([project_id])

        # user_file_list = models.fileinfo.objects.filter(file_user__user_name=user).values("file_id", "file_url",
        #                                                                                       "file_user__user_name",
        #                                                                                       "file_project__project_alias",
        #                                                                                       "file_ctime",
        #                                                                                       "file_md5").order_by(
        #         '-file_id')
        # info["user_file_list"] = user_file_list
        models.log_record.objects.create(user_name=user,log_content="项目%s下%s更新上传" %(project_name,userfile.name),log_ctime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
        # return render(request,"other/myfile.html",info)
        return  redirect("/user/myfile/")
    else:
        user = request.session.get("user_name")
        user_ower = request.GET.get("user")
        project_id = request.GET.get("project_id")
        if user_show_status == "0":
            if user_ower == None and project_id == None:

                user_file_list = models.fileinfo.objects.filter(file_user__user_name=user).values("file_id", "file_url",
                                                                                                  "file_user__user_alias",
                                                                                                  "file_project__project_alias",
                                                                                                  "file_ctime","file_md5",
                                                                                                  "file_cdn_status",
                                                                                                  "file_cdn_time",
                                                                                                  "file_path","web_path").order_by('-file_id')

                info["user_file_list"] = user_file_list
            else:

                user_file_list = models.fileinfo.objects.filter(file_user__user_name=user_ower,file_project__project_id=project_id).values("file_id", "file_url",
                                                                                                  "file_user__user_alias",
                                                                                                  "file_project__project_alias",
                                                                                                  "file_ctime",
                                                                                                  "file_md5" ,
                                                                                                  "file_cdn_status",
                                                                                                  "file_cdn_time",
                                                                                                  "file_path","web_path").order_by('-file_id')
                info["user_file_list"] = user_file_list
        elif user_show_status == "1":
            if user_ower == None and project_id == None:

                user_file_list = models.fileinfo.objects.filter(file_user__user_name=user).values("file_id", "file_url",
                                                                                                  "file_user__user_alias",
                                                                                                  "file_project__project_alias",
                                                                                                  "file_ctime",
                                                                                                  "file_md5",
                                                                                                  "file_cdn_status",
                                                                                                  "file_cdn_time",
                                                                                                  "file_path","web_path").order_by('-file_id')

                info["user_file_list"] = user_file_list
            else:

                user_file_list = models.fileinfo.objects.filter(
                                                                file_project__project_id=project_id).values("file_id",
                                                                                                            "file_url",
                                                                                                            "file_user__user_alias",
                                                                                                            "file_project__project_alias",
                                                                                                            "file_ctime",
                                                                                                            "file_md5",
                                                                                                            "file_cdn_status",
                                                                                                            "file_cdn_time",
                                                                                                            "file_path","web_path").order_by('-file_id')
                info["user_file_list"] = user_file_list
        elif user_show_status == "2":
            if user_ower == None and project_id == None:

                user_file_list = models.fileinfo.objects.values("file_id", "file_url","file_user__user_alias",
                                                                "file_project__project_alias",
                                                                "file_ctime",
                                                                "file_md5",
                                                                "file_cdn_status",
                                                                "file_cdn_time",
                                                                "file_path","web_path").order_by('-file_id')

                info["user_file_list"] = user_file_list
            else:

                user_file_list = models.fileinfo.objects.filter(file_project__project_id=project_id).values("file_id",
                                                                                                            "file_url",
                                                                                                            "file_user__user_alias",
                                                                                                            "file_project__project_alias",
                                                                                                            "file_ctime",
                                                                                                            "file_md5",
                                                                                                            "file_cdn_status",
                                                                                                            "file_cdn_time",
                                                                                                            "file_path","web_path").order_by('-file_id')
                info["user_file_list"] = user_file_list
        return render(request,"other/myfile.html",info)

def delmyfile(request):
    if request.method == "GET":
        user_name = request.session.get("user_name")
        file_id =  request.GET.get("file_id")
        file_info =  models.fileinfo.objects.filter(file_id=file_id).values("file_name","file_project__project_name")[0]
        file_name = file_info["file_name"]
        from fileadmin import settings
        base_dir=settings.STATICFILES_DIRS
        file_project = file_info["file_project__project_name"]
        os.remove("%s/apk/%s/%s" %(base_dir[0],file_project,file_name))
        models.fileinfo.objects.filter(file_id=file_id).delete()
        models.log_record.objects.create(user_name=user_name,log_content="项目%s下的文件%s被删除" %(file_project,file_name),log_ctime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
        return redirect("/user/myfile/")
def sysconfig(request):
    user = request.session.get("user_name")
    info={"user_name":user}
    if request.method == "GET":
        url_status =  models.sysconfig.objects.values().count()
        if url_status == 0:
            return render(request, "other/sysconfig.html", info)
        else:
            url =  models.sysconfig.objects.values()[0]
            info["url"] =  url
            cdn_list = models.cdnconfig.objects.values("cdn_id","cdn_name","cdn_enable")
            info["cdn_list"] = cdn_list
            return render(request,"other/sysconfig.html",info)
    else:
        apk_url = request.POST.get("apk_url")
        status =  models.sysconfig.objects.count()
        cdn_id = request.POST.get("cdn_enable")
        if status == 0:
            models.sysconfig.objects.create(apk_url=apk_url)
        else:
            models.sysconfig.objects.update(apk_url=apk_url)
        models.cdnconfig.objects.update(cdn_enable=0)
        models.cdnconfig.objects.filter(cdn_id=cdn_id).update(cdn_enable=1)
        models.fileinfo.objects.update(web_path=apk_url)
        return  redirect("/user/sysconfig/")


def log(request):
    if request.method == "GET":
        models.log_record.objects.all().delete()
    return redirect("/user/login")

